<?php

namespace app\api\controller;

use app\BaseController;
use app\common\util\MyException;
use stdClass;
use think\facade\Db;

class Alipay extends BaseController
{
    /**
     * 构建支付宝支付数据
     * @param string $order_sn 订单编号
     * @param string $amount 订单金额
     * @param string $body 描述
     */
    public function createData($order_sn,$amount,$body="城市牧场订单"){
        require_once root_path('payment/alipay-sdk')."aop/request/AlipayTradeAppPayRequest.php";
//        $aop = $this->getAop();
        $aop = $this->getAopCert();
        $request = new \AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = "{\"subject\": \"$body\","
            . "\"out_trade_no\": \"$order_sn\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"$amount\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $request->setNotifyUrl(url('Alipay/notify_url')->domain(true)->build());
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $result = $aop->sdkExecute($request);
        return $result;
    }
    /**
     * 支付宝转账
     * @param string $order_sn 订单编号
     * @param float $money 转账金额
     * @param string $zhifubao 支付宝账号
     * @param string $zfb_realname 支付宝姓名
     * @param string $remark 备注
     */
    public function transfer($order_sn,$money,$zhifubao,$zfb_realname,$remark){
        $dk_appid=getSysConfig('cash.zfb_transfer_appId');
        $dk_protected_key=getSysConfig('cash.zfb_transfer_rsaPrivateKey');
        require_once root_path('payment/alipay-sdk')."aop/AopClient.php";
        require_once root_path('payment/alipay-sdk')."aop/AopCertClient.php";
        require_once root_path('payment/alipay-sdk')."aop/AopCertification.php";
        require_once root_path('payment/alipay-sdk')."aop/AlipayConfig.php";
        require_once root_path('payment/alipay-sdk')."aop/request/AlipayFundTransUniTransferRequest.php";
        $appCertPath = root_path('payment/alipay-sdk')."cert/appCertPublicKey_2021003144648072.crt";
        $alipayCertPath = root_path('payment/alipay-sdk')."cert/alipayCertPublicKey_RSA2.crt";
        $rootCertPath = root_path('payment/alipay-sdk')."cert/alipayRootCert.crt";
        //请填写您的应用私钥，例如：MIIEvQIBADANB ... ...
        $privateKey=trim($dk_protected_key);
        $alipayConfig = new \AlipayConfig();
        $alipayConfig->setPrivateKey($privateKey);
        $alipayConfig->setServerUrl("https://openapi.alipay.com/gateway.do");
        $alipayConfig->setAppId(trim($dk_appid));
        $alipayConfig->setCharset("UTF-8");
        $alipayConfig->setSignType("RSA2");
        $alipayConfig->setEncryptKey("");
        $alipayConfig->setFormat("json");
        $alipayConfig->setAppCertPath($appCertPath);
        $alipayConfig->setAlipayPublicCertPath($alipayCertPath);
        $alipayConfig->setRootCertPath($rootCertPath);
        $alipayClient = new \AopCertClient($alipayConfig);
        $alipayClient->isCheckAlipayPublicCert = true;
        $request = new \AlipayFundTransUniTransferRequest();
        $request->setBizContent("{".
            "\"out_biz_no\":\"$order_sn\",".
            "\"remark\":\"$remark\",".
            "\"business_params\":\"{\\\"payer_show_name_use_alias\\\":\\\"true\\\"}\",".
            "\"biz_scene\":\"DIRECT_TRANSFER\",".
            "\"payee_info\":{".
            "\"identity\":\"$zhifubao\",".
            "\"identity_type\":\"ALIPAY_LOGON_ID\",".
            "\"name\":\"$zfb_realname\"".
            "},".
            "\"trans_amount\":\"$money\",".
            "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",".
            "\"order_title\":\"$remark\"".
            "}");
        $responseResult = $alipayClient->execute($request);
        $responseApiName = str_replace(".","_",$request->getApiMethodName())."_response";
        $response = $responseResult->$responseApiName;
        if(!empty($response->code)&&$response->code==10000){
            return ['code'=>1,'msg'=>'转账成功'];
        } else{
            $resultMsg = $response->msg;
            return ['code'=>0,'msg'=>$resultMsg];
        }
    }
    //转账 旧方法
    private function transfer1($order_sn,$money,$zhifubao,$zfb_realname,$remark){
        $dk_appid=getSysConfig('cash.zfb_transfer_appId');
        $dk_public_key=getSysConfig('cash.zfb_transfer_alipayrsaPublicKey');
        $dk_protected_key=getSysConfig('cash.zfb_transfer_rsaPrivateKey');
        require_once root_path('payment/alipay-sdk')."aop/AopCertClient.php";
        require_once root_path('payment/alipay-sdk')."aop/AopClient.php";
        require_once root_path('payment/alipay-sdk')."aop/AopCertification.php";
        require_once root_path('payment/alipay-sdk')."aop/request/AlipayFundTransUniTransferRequest.php";
        $aop = new \AopCertClient();
        $appCertPath = root_path('payment/alipay-sdk')."cert/appCertPublicKey_2021003144648072.crt";
        $alipayCertPath = root_path('payment/alipay-sdk')."cert/alipayCertPublicKey_RSA2.crt";
        $rootCertPath = root_path('payment/alipay-sdk')."cert/alipayRootCert.crt";
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = trim($dk_appid);
        $aop->rsaPrivateKey = trim($dk_protected_key);
        $aop->format = "json";
        $aop->charset= "GBK";
        $aop->signType= "RSA2";
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
        $request = new \AlipayFundTransUniTransferRequest();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"".$order_sn."\"," .
            "\"trans_amount\":\"".$money."\"," .
            "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," .
            "\"biz_scene\":\"DIRECT_TRANSFER\"," .
            "\"order_title\":\"$remark\"," .
            "\"payee_info\":{" .
            "\"identity\":\"".$zhifubao."\"," .
            "\"identity_type\":\"ALIPAY_LOGON_ID\"," .
            "\"name\":\"".$zfb_realname."\"" .
            "    }," .
            "\"remark\":\"$remark\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        $resultMsg = $result->$responseNode->sub_msg;
        if(!empty($resultCode) && $resultCode == 10000){
            return ['code'=>1,'msg'=>'转账成功'];
        } else {
            return ['code'=>0,'msg'=>$resultMsg];
        }
        /*
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = trim($dk_appid);
        $aop->rsaPrivateKey = trim($dk_protected_key);
        $aop->alipayrsaPublicKey=trim($dk_public_key);
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayFundTransToaccountTransferRequest();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"".$order_sn."\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"".$zhifubao."\"," .
            "\"amount\":\"".$money."\"," .
            "\"payee_real_name\":\"".$zfb_realname."\"," .
            "\"remark\":\"$remark\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        $resultMsg = $result->$responseNode->sub_msg;
        if(!empty($resultCode) && $resultCode == 10000){
            return ['code'=>1,'msg'=>'转账成功'];
        } else {
            return ['code'=>0,'msg'=>$resultMsg];
        }*/
    }
    //支付宝异步通知
    public function notify_url(){
        $aop = $this->getAopCert(false);
        $post=input('post.');
        $flag = $aop->rsaCheckV1($post, NULL, "RSA2");
        $trade_status=input('trade_status');//交易状态
        //商户订单号
        $out_trade_no = $post['out_trade_no'];
        //支付宝交易号
        $trade_no = $post['trade_no'];
        if ($flag){//验证成功
            if ($trade_status=="TRADE_SUCCESS" || $trade_status=="TRADE_FINISHED"){
                update_pay_status($out_trade_no,$trade_no);
                echo "success"; // 告诉支付宝处理成功
            }else{
                echo "fail"; //验证失败
            }
        }else{
            echo "fail"; //验证失败
        }
    }
    //公钥证书方式
    private function getAopCert($throw=true){
        $where['code']='alipayMobile';
        if ($throw){
            $where['status']=1;
        }
        $plugin=Db::name('plugin')->where($where)->find();
        if (empty($plugin)){
            throw new MyException("支付宝支付暂未开放");
        }
        $config_value=unserialize($plugin['config_value']);
        require_once root_path('payment/alipay-sdk')."aop/AopCertClient.php";
        require_once root_path('payment/alipay-sdk')."aop/AopCertification.php";
        require_once root_path('payment/alipay-sdk')."aop/AlipayConfig.php";

        $appCertPath = root_path('payment/alipay-sdk')."cert/appCertPublicKey_2021003144648072.crt";
        $alipayCertPath = root_path('payment/alipay-sdk')."cert/alipayCertPublicKey_RSA2.crt";
        $rootCertPath = root_path('payment/alipay-sdk')."cert/alipayRootCert.crt";
        //请填写您的应用私钥，例如：MIIEvQIBADANB ... ...
        $privateKey=trim($config_value['alipay_private_key']);
        $alipayConfig = new \AlipayConfig();
        $alipayConfig->setPrivateKey($privateKey);
        $alipayConfig->setServerUrl("https://openapi.alipay.com/gateway.do");
        $alipayConfig->setAppId(trim($config_value['alipay_appid']));
        $alipayConfig->setCharset("UTF-8");
        $alipayConfig->setSignType("RSA2");
        $alipayConfig->setEncryptKey("");
        $alipayConfig->setFormat("json");
        $alipayConfig->setAppCertPath($appCertPath);
        $alipayConfig->setAlipayPublicCertPath($alipayCertPath);
        $alipayConfig->setRootCertPath($rootCertPath);
        $alipayClient = new \AopCertClient($alipayConfig);
        $alipayClient->isCheckAlipayPublicCert = true;
        return $alipayClient;
    }
    //公钥方式
    private function getAop($throw=true){
        $where['code']='alipayMobile';
        if ($throw) {
            $where['status']=1;
        }
        $plugin=Db::name('plugin')->where($where)->find();
        if (empty($plugin)){
            throw new MyException("支付宝支付暂未开放");
        }
        $config_value=unserialize($plugin['config_value']);
        require_once root_path('payment/alipay-sdk')."aop/AopClient.php";
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = trim($config_value['alipay_appid']);
        $aop->rsaPrivateKey = trim($config_value['alipay_private_key']);
        $aop->alipayrsaPublicKey=trim($config_value['alipay_public_key']);
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        return $aop;
    }
}
